package org.lzuploader.gui.listeners.login;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Shell;
import org.lzuploader.gui.WLogin;

/**
 * Class used to detect that the user has pressed the enter key.
 * @author Emmanuel Cron
 *
 */
public class EnterKeyListener implements KeyListener
{
    /** Logger of this class. */
    private static Log log = LogFactory.getLog(EnterKeyListener.class);
    
    /** Last key pressed by the user. */
    private static int key;

    /**
     * When the user presses a key.
     * @param e Associated event.
     */
    public void keyPressed(final KeyEvent e)
    {
        key = e.keyCode;
    }

    /**
     * When the user releases a key.
     * @param e Associated event.
     */
    public void keyReleased(final KeyEvent e)
    {
        if (e.keyCode == key)
        {
            if (e.keyCode == SWT.CR)
            {
                log.debug("User pressed the enter key.");
                
                log.trace("Fetching data.");
                
                Shell wLoginShell = null;
                for (int i = 0 ; i < e.display.getShells().length ; i++)
                {
                    if (e.display.getShells()[i].getData() instanceof WLogin)
                    {
                        wLoginShell = e.display.getShells()[i];
                        break;
                    }
                }
                
                new OkSelectionListener().processAuthentificationAndUpload(wLoginShell);
            }
        }
        
        key = SWT.NONE;
    }

}
